package gre.core;

import gre.db.*;
import java.sql.*;
import java.util.*;
import java.io.*;

/**
 *
 * @author nacuong
 */
public class WordInserter {

  /**
   * Given a string of the form word|meaning|setence1@sentence2@...
   * Insert data to the table
   * 
   * @param stmt  sql stmt executer
   * @param data  the data in the form given above
   * @param confirm decide whether to ask for confirmation
   * @param append  decide whether to append data to back up file
   * @throws SQLException
   * @throws IOException
   */
  public static void insert(Statement stmt, String data, boolean confirm, boolean append) throws SQLException, IOException {
    Scanner sc = new Scanner(System.in);
    String[] datas = data.split("\\|");
    if (datas.length >= 2) {
      String word = datas[0];
      String meaning = datas[1];
      String[] sentences = new String[0];
      if (datas.length == 3)
        sentences = datas[2].split("@");
      

      boolean insertWord = true;
      if (confirm) {
        System.out.println("Please confirm that you want to insert word: " + word
                + " with meaning: " + meaning + "(yes|no)");
        if (!sc.nextLine().toLowerCase().equals("yes")) {
          insertWord = false;
        }
      }

      if (insertWord) {
        DBInserter.insertWord(stmt, word, meaning);
        if (append) AutoBackup.appendData(data);
        for (String sentence : sentences) {
          boolean insertSentence = true;
          if (confirm) {
            System.out.println("Please confirm that you want to insert sentece: " + sentence + "(yes|no)");
            if (!sc.nextLine().toLowerCase().equals("yes")) {
              insertSentence = false;
            }
          }
          if (insertSentence)
            DBInserter.insertSentence(stmt, word, sentence);
        }
      }
    }
  }

  /**
   * Insert all datas from filePath into the table.
   * Data are of the form word|meaning|sentence1@sentence2...
   *
   * @param stmt
   * @param filePath
   * @throws FileNotFoundException
   * @throws SQLException
   * @throws IOException
   */
  public static void insertFormFile(Statement stmt, String filePath) throws SQLException, IOException {
    File file = new File(filePath);
    File backupFile = new File(DBHelper.getCurrentPath() + AutoBackup.backupFile);
    Scanner sc = new Scanner(file);
    boolean append = !file.getAbsolutePath().equals(backupFile.getAbsolutePath());

    while (sc.hasNextLine()) {
      insert(stmt, sc.nextLine(), false, append);
    }
  }
}
